/*
 * This Class make the connection to the database sim.
 */
package sim.DAL;

import java.sql.*;

/**
 *
 * @author rafik
 */

public class DBConnection implements java.io.Serializable {
private String login;
private String password;
private String hostname;
private String port;
private String databaseName;
private Connection conn;

// Default parametres connection
public DBConnection() {
    setHostname("127.0.0.1");
    setPort("3306");
    setDatabaseName("sim");
    setLogin("root");
    setPassword("password");
}

// Method to setup connection with parameters

public void setLogin(String login) {
    this.login = login;
}
public void setPassword(String password) {
    this.password = password;
}
public void setHostname(String hostname) {
    this.hostname = hostname;
}
public void setPort(String port) {
    this.port = port;
}
public void setDatabaseName(String databaseName) {
    this.databaseName = databaseName;
}

// Return a connection
public Connection getConnection() {
    if(establishConnection()) {
        return conn;
    }
    else {
        return null;
    }
}

public ResultSet executeSql(String sqlStatement){
    try {
        Statement st = getConnection().createStatement();
        ResultSet rs = st.executeQuery(sqlStatement);

        return rs;
    } catch (SQLException sqlexp) {
        System.err.println(sqlexp.getMessage());
        return null;
    }
}
private String buildUrlJdbc() {
    String url;
    url = "jdbc:mysql://"+ hostname + ":" + port + "/" + databaseName;

    url += "?user=" + login + "&password=" + password;
    return url;
}

private boolean establishConnection() {
    boolean status = false;

    try {
       Class.forName("com.mysql.jdbc.Driver").newInstance();
       conn = DriverManager.getConnection(buildUrlJdbc());
       status = true;
    } catch (Exception e) {
        status = false;
        System.err.println("Exception: " + e + " " + buildUrlJdbc());
    }

    return status;
}

}